import React, { Component, createRef } from 'react'

type Props = {
    label: string | 'default label',
    type: 'submit' | 'button',
    onClick: () => any
}

class FancyButton extends Component<Props> {
    private myRef = createRef<HTMLButtonElement>()
    render() {
        const { label, type, onClick } = this.props
        return (
            <button
                className="FancyButton"
                type={type}
                onClick={onClick}
                ref={this.myRef}
            >{label || 'label'}</button>
        )
    }
}

interface LogMeta { forwardRef?: any }

// 场景一、通过高阶组件转发
const ForwardRefProps: any = (WrappedComponent: any) => {
    class LogProps extends React.Component<LogMeta> {
        componentDidMount() {
            console.log(this.props.forwardRef, 888)
        }
        componentDidUpdate(prevProps: any) {
            console.log('old props:', prevProps)
            console.log('new props:', this.props)
        }
        render() {
            const { forwardRef, ...rest } = this.props
            return <WrappedComponent ref={forwardRef} {...rest} />
        }
    }
    return React.forwardRef((props, ref) => {
        // 将 ref 作为参数传递给 LogProps 的 props.forwardRef
        // LogProps 内部再将 props.forwardRef 传递给 Button 的 ref
        // 这样外层 通过转发就可以拿到 Button 的 节点 ref
        return <LogProps forwardRef={ref} {...props} />
    })
}

// 场景二、不通过 forwardRef 转发
const CommonProps: any = (Component: any) => {
    class LogProps extends React.Component<LogMeta> {
        componentDidUpdate(prevProps: any) {
            console.log('old props:', prevProps)
            console.log('new props:', this.props)
        }
        render() {
            return <Component {...this.props} />
        }
    }
    return LogProps
}

export default ForwardRefProps(FancyButton)